package com.lengyu.iottransfer.gateway.security;

import com.alibaba.fastjson.JSONObject;
import com.lengyu.iottransfer.gateway.entity.Permission;
import com.lengyu.iottransfer.gateway.entity.Role;
import com.lengyu.iottransfer.gateway.security.rest.dto.JwtUser;
import com.lengyu.iottransfer.gateway.service.IPermissionService;
import com.lengyu.iottransfer.gateway.service.IRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;


@Configuration
public class CustomPermissionEvaluator implements PermissionEvaluator {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    @Override
    public boolean hasPermission(Authentication authentication, Object targetUrl, Object permission) {
        String jwtUserStr = String.valueOf(authentication.getPrincipal());
        // 获得loadUserByUsername()方法的结果
        JwtUser jwtUser = JSONObject.toJavaObject(JSONObject.parseObject(jwtUserStr),JwtUser.class);
        // 获得用户授权
        Collection<GrantedAuthority> authorities = jwtUser.getAuthorities();

        // 遍历用户所有角色
        for(GrantedAuthority authority : authorities) {
            String roleCode = authority.getAuthority();
            Role role = roleService.getByCode(roleCode);
            String roleId;
            if(role != null){
                roleId = role.getId();
            }
            else{
                continue;
            }

            // 得到角色所有的权限
            List<Permission> permissionList = permissionService.getByRoleId(roleId);
            if (null == permissionList) {
                continue;
            }

            // 遍历permissionList
            for(Permission sysPermission : permissionList) {
                String pstr = sysPermission.getCode();
                // 判空
                if (StringUtils.isBlank(pstr)) {
                    continue;
                }
                // 如果访问的url和权限相符，返回true
                if (pstr.equals(permission)) {
                    return true;
                }
            }
        }

        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable,
            String targetUrl, Object permission) {
        return false;
    }
}
